package com.example.eci_quartz.cloudcc.impl;

import com.example.eci_quartz.cloudcc.commcon.CommonMethod;
import com.example.eci_quartz.cloudcc.commcon.DataGroupUtil;
import com.example.eci_quartz.cloudcc.commcon.DateUtil;
import com.example.eci_quartz.cloudcc.dao.DefaultConnectionFactory;
import com.example.eci_quartz.cloudcc.dao.baseDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 *同步设备信息下EPP
 */
public class EppImpl3 extends baseDao {

	SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat sdfY= new SimpleDateFormat("yyyy");
	SimpleDateFormat sdfM= new SimpleDateFormat("MMdd");
	static String binding = InsertXMInfo();
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String upsertEpp(){
		Connection conn=null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Map> updatelist =null;
		List<Map> insertlist =null;

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Calendar cal=Calendar.getInstance();
	    cal.set(Calendar.DATE,cal.get(Calendar.DATE)-2000);
	    String firstDay=format.format(cal.getTime());
		String info = "false";
		Map<String, Map> orderMap=null;//map<销售订单编号，销售订单对象值>
		Map<String,Map> rsMap=null;
		String sql="select * FROM LIBJ49FSMS.EPPNEW "
				+" WHERE LSMN8 <'"+firstDay+"' or LSMN8 IS NULL";
		int count=1;
		try {
			Map typeCodeMap=geteppdmlxMap();//查询EPP类型代码
			conn = new DefaultConnectionFactory().getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			orderMap = new HashMap<String, Map>();// map<销售订单编号，销售订单对象值>
			rsMap=new HashMap<String,Map>();//map<零件号，零件数据>从DBS查询出来的
			String codes="";//项目编号数组
			String sns="";//设备数组
			if (rs != null) {
				while (rs.next()) {
					Map mapObj=new HashMap();
					//设备序列号
					String sn=(rs.getString("EQMFSN") == null ? "" : rs.getString("EQMFSN")+ "").trim();
					mapObj.put("sn",sn);
					//保修类型代码
					String typeCode=(rs.getString("WATPCD") == null ? "" : rs.getString("WATPCD")+ "").trim();

					mapObj.put("name",typeCode);
					mapObj.put("sfjktb", 1);
					//EPP保修代码EPP Warranty Code
					mapObj.put("WarrantyCode", typeCodeMap.get(typeCode));
					//区划
					mapObj.put("Division", (rs.getString("WARDIV") == null ? "" : rs.getString("WARDIV")+ "").trim());
					//EPP保修类型
					String DS5=(rs.getString("DS5") == null ? "" : rs.getString("DS5")+ "").trim();
					mapObj.put("WarrantyType", DS5);
					//开始时间
					String ksrq=(rs.getString("WRSTD8") == null ? "" : rs.getString("WRSTD8")+ "").trim();
			        mapObj.put("StartDate",DateUtil.getDatetoStringUtil(ksrq));
			        //结束时间
			        String jsrq=(rs.getString("WAEXD8") == null ? "" : rs.getString("WAEXD8")+ "").trim();
			        String jsrqnew=DateUtil.getDatetoStringUtil(jsrq);
			        mapObj.put("ExpirationDate",jsrqnew);
					mapObj.put("StartSMU", (rs.getString("SMUSTR") == null ? "" : rs.getString("SMUSTR")+ "").trim());
					//Expiration SMU
					mapObj.put("ExpirationSMU", (rs.getString("SMUEND") == null ? "" : rs.getString("SMUEND")+ "").trim());
					//创建时间
					mapObj.put("dbscjsj", DateUtil.getDatetoStringUtil((rs.getString("DTSYS8") == null ? "" : rs.getString("DTSYS8")+ "").trim()));
					//修改时间
					mapObj.put("dbsxgsj", DateUtil.getDatetoStringUtil((rs.getString("LSMN8") == null ? "" : rs.getString("LSMN8")+ "").trim()));
					String name="";
					if((sn!=null&&!"".equals(sn))&&(typeCode!=null&&!"".equals(typeCode))){
						name=typeCode+"-"+sn+"-"+jsrqnew;
						mapObj.put("name",name);//epp编码
						codes+="'"+name+"',";//项目编号数组
						//设备数组
						sns+="'"+sn+"',";
						rsMap.put(name, mapObj);

					}
			}
			 String result="";
			 //判断是否存在
		     if(codes!=null&&!"".equals(codes)){
					//查询系统中全部的标准工时
					String data_query = "serviceName=cqlQuery&objectApiName=eppybyy" +
							"&expressions=select id,name from eppybyy  " +
							"where name is not null and name in ("+codes.substring(0, codes.length()-1)+") " +
							" and is_deleted='0'&binding=";//查询设备信息
					String order_datas="";
					String orderinfo = operate(data_query+ binding);
					//判断binding是否失效，如果失效，就重新获取
				    JSONObject fromObject =null;
					if(CommonMethod.isJSONValid(orderinfo)){
						fromObject = JSONObject.fromObject(orderinfo);
						result= fromObject.getString("result")==null?"":fromObject.getString("result");
					}
					if(!"true".equals(result)){

						binding = InsertXMInfo();

						orderinfo=operate(data_query+binding);
						if(CommonMethod.isJSONValid(orderinfo)){
							fromObject = JSONObject.fromObject(orderinfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}

					}
					String returninfo = "[" + orderinfo + "]";// 手动转换成json格式，方便取值
					if (!"[]".equals(returninfo)&&orderinfo!=null) {
						JSONArray brand_list = JSONArray.fromObject(returninfo);
						if (brand_list != null) {
							for (int j = 0; j < brand_list.size(); j++) {
								JSONObject brandInfo = (JSONObject) brand_list.get(j);
								String Result = brandInfo.get("result") == null ? ""
										: brandInfo.get("result") + "";// 获取返回值
								String date = brandInfo.get("data") == null ? ""
										: brandInfo.get("data") + "";// 获取返回值
								if ("true".equals(Result)) {
									order_datas = date;
								}
							}
						}
					}
					// 查询CRM系统中EPP的信息并存入到map中
					if (order_datas != "[]") {
						JSONArray datas_list = JSONArray.fromObject(order_datas);
						if (datas_list != null) {
							for (int i = 0; i < datas_list.size(); i++) {
								JSONObject accObj = (JSONObject) datas_list.get(i);
								JSONObject order_newObj = new JSONObject();//新的json，只存id，编号
								//设备编号
							    String code= (accObj.get("name")==null? "" : accObj.get("name").toString()).trim();
							    if(code!=null&&!"".equals(code)){
							    	order_newObj.put("id", accObj.get("id"));
									order_newObj.put("name", code);
									orderMap.put(code,order_newObj);
							    }
							}
						}
					}
			  }
			JSONObject order_newObj = new JSONObject();//新的json，只存id，编号
			order_newObj.put("result",result);
			orderMap.put("result",order_newObj);

			//判断零件是新增还是更新
			if(rsMap.size()>0&&rsMap!=null){
				updatelist = new ArrayList<Map>();
				insertlist = new ArrayList<Map>();
				Map  sbMaps=EquipmentImpl.getsbglMap(sns);	//查询设备集合
			   for(String code:rsMap.keySet()){
				   if(orderMap!=null&&orderMap.get("result").containsValue("true")){
					   Map ljObj=rsMap.get(code);//获取DBS中的客户数据
					   if (orderMap.containsKey(code)) {// 更新设备信息
						   Map eppMap =orderMap.get(code);
						   Map  sbMap=(Map) sbMaps.get(ljObj.get("sn"));
						   if(sbMap!=null&&!"".equals(sbMap)) {
							   ljObj.put("sbxlh", (sbMap.get("id") == null ? "" : sbMap.get("id")+ "").trim());
						   }
						   ljObj.put("id",eppMap.get("id"));
						   updatelist.add(ljObj);
						}else {// 新建设备信息
							Map  sbMap=(Map) sbMaps.get(ljObj.get("sn"));
						   if(sbMap!=null&&!"".equals(sbMap)) {
							   ljObj.put("sbxlh", (sbMap.get("id") == null ? "" : sbMap.get("id")+ "").trim());
						   }
							insertlist.add(ljObj);
						 }
					 }

				}
			}
			//插入新的设备信息
			if (insertlist!=null&&insertlist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataOneGroup(insertlist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayInsert = JSONArray.fromObject(amList);
						String jsonstr=jsonArrayInsert.toString();
						jsonstr = java.net.URLEncoder.encode(jsonstr, "UTF-8");
						String data_insert = "serviceName=insert&objectApiName=eppybyy&data="+jsonstr+"&binding=";//insertLt批量插入，不走触发器
			            String insertInfo=operate(data_insert+ binding);//执行CRM系统插入操作insert

						//判断binding是否失效，如果失效，就重新获取
			            JSONObject fromObject =null;
						if(CommonMethod.isJSONValid(insertInfo)){
							fromObject = JSONObject.fromObject(insertInfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){

							binding = InsertXMInfo();

							insertInfo=operate(data_insert+binding);

						}

					    info="insert_success";
					}
				}
			}
			//更新系统中的设备信息
			if (updatelist!=null&&updatelist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(updatelist);
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayUpdate = JSONArray.fromObject(amList);
						String jsonstr_update=jsonArrayUpdate.toString();
						jsonstr_update = java.net.URLEncoder.encode(jsonstr_update, "UTF-8");
						String data_update = "serviceName=updateLt&objectApiName=eppybyy&data="+jsonstr_update+"&binding=";//updateLt批量更新，不走触发器
			            String updateInfo=operate(data_update+binding);//执行CRM系统插入操作insert

						//判断binding是否失效，如果失效，就重新获取
			            JSONObject fromObject =null;
						if(CommonMethod.isJSONValid(updateInfo)){
							fromObject = JSONObject.fromObject(updateInfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){

							binding = InsertXMInfo();

							updateInfo=operate(data_update+binding);
						}

			            info="update_success";
					}
				}
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return info;
	}

	/**
	  *查询EPP代码类型  eppdmlx
	  *
	  * */
	@SuppressWarnings("rawtypes")
	public static Map geteppdmlxMap(){
		String data_query = "serviceName=cqlQuery&objectApiName=eppdmlx" +
				"&expressions=select id,name from eppdmlx " +
				"where name is not null and is_deleted='0' &binding=";
		String khinfo = "";//查询返回来的值
		String kh_datas = "";//查询成功返回来的数据
		Map<String, String> ckMap = null;
		try {
			ckMap = new HashMap<String, String>();// map<客户编号，客户对象值>
			khinfo = operate(data_query+binding);//通过http方式调用咱们平台的查询方法
			//判断binding是否失效，如果失效，就重新获取
		    JSONObject fromObject =null;
		    String result="";
			if(CommonMethod.isJSONValid(khinfo)){
				fromObject = JSONObject.fromObject(khinfo);
				result= fromObject.getString("result")==null?"":fromObject.getString("result");
			}
			if(!"true".equals(result)){

				binding = InsertXMInfo();

				khinfo=operate(data_query+binding);
			}

			String returninfo = "[" + khinfo + "]";// 手动转换成json格式，方便取值
			if (!"[]".equals(returninfo)&&khinfo!=null) {
				JSONArray brand_list = JSONArray.fromObject(returninfo);
				if (brand_list != null) {
					for (int j = 0; j < brand_list.size(); j++) {
						JSONObject brandInfo = (JSONObject) brand_list.get(j);
						String Result = brandInfo.get("result") == null ? ""
								: brandInfo.get("result") + "";// 获取返回值
						String date = brandInfo.get("data") == null ? ""
								: brandInfo.get("data") + "";// 获取查询结果的返回值
						if ("true".equals(Result)) {
							kh_datas = date;
						}
					}
				}
			}
			// 查询crm系统中客户的信息并存入到map中
			if (kh_datas != "[]"&&!"".equals(kh_datas)) {
				JSONArray datas_list = JSONArray.fromObject(kh_datas);
				if (datas_list != null) {
					for (int i = 0; i < datas_list.size(); i++) {
						JSONObject accObj = (JSONObject) datas_list.get(i);
						String name=(accObj.get("name")==null?"":accObj.get("name").toString()).trim();
						if(name!=null&&!"".equals(name)){
							ckMap.put(accObj.get("name").toString(), accObj.get("id").toString());
						}
					}
				}
			}
		}catch (Exception e) {
			System.out.println("geteppdmlxMap"+e.getMessage());
		}
		return ckMap;
	}


}
